package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.common.fastdfs.FastDFSClientUtil;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import com.usian.wemedia.utils.KODOClientUtil;
import com.usian.wemedia.utils.OSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClientUtil fastDFSClientUtil;

    @Value("${fdfs.url}")
    private String fasturl;


    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile,Integer status) {
        //1.检查参数
        if(multipartFile == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"文件为空");
        }
        String url = null;

            if (status == 5) {
                try {
                    //2.上传图片到fasfdfs
                    url = fastDFSClientUtil.uploadFile(multipartFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (status == 2) {
                url = KODOClientUtil.saveImage(multipartFile);
            } else {
                OSSClientUtil ossClientUtil = new OSSClientUtil();
                url = ossClientUtil.saveImage(multipartFile);
            }

        //3. 保存到数据库中
        WmUser user = WmThreadLocalUtils.getUser();
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(user.getId());
        wmMaterial.setUrl(url);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short)0); // 图片
        wmMaterial.setIsCollection((short)0); // 未收藏
        this.save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {


        if(dto==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"对象为空");
        }
        // 分页初始化
        dto.checkParam();
        // 根据userID 进行查询  收藏  时间倒序
        //获取当前登录的用户
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,uid);
        //是否收藏
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        lambdaQueryWrapper.orderByDesc(WmMaterial::getIsCollection,WmMaterial::getCreatedTime);
        // order by iscollection desc,createtime desc
        IPage<WmMaterial> iPage  = this.page(new Page<>(dto.getPage(),dto.getSize()),lambdaQueryWrapper);
        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)iPage.getTotal());
        List<WmMaterial> datas = iPage.getRecords();

        // 拼接前缀
        datas = datas.stream().map(item->{
            item.setUrl(fasturl+item.getUrl());
            return item;
        }).collect(Collectors.toList());


        responseResult.setData(datas);

        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        if(id==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"删除的Id不能为空");
        }
        //检查图片时候被引用
        Integer count = wmNewsMaterialMapper.selectCount(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getMaterialId,id));
        if(count>0){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前素材被引用，不能删除");
        }
        WmMaterial wmMaterial =  this.getById(id);
        if(wmMaterial==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前素材Id有误，请检查");
        }
        if(!wmMaterial.getUserId().equals(WmThreadLocalUtils.getUser().getId())){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"当前用户信息有误");
        }
        // 证明可以删除
        this.removeById(id);
        // 删除 FastDFS
        fastDFSClientUtil.delFile(wmMaterial.getUrl());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 公用的修改,收藏
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"Id不能为空" );
        }
        // update set isconllection = type  where id= ? and userid= ?
        this.update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,WmThreadLocalUtils.getUser().getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
